import os
import django
from django.db import connection

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')  # 假设项目名是 WxApi，需要确认 settings 路径
# 根据路径 f:\和臻OA\backend\WxApi\models.py，项目根目录可能是 f:\和臻OA\backend
# 假设 manage.py 在 f:\和臻OA\backend

import sys
sys.path.append(os.getcwd())

# Setup Django
try:
    from django.core.management import execute_from_command_line
except ImportError as exc:
    raise ImportError(
        "Couldn't import Django. Are you sure it's installed and "
        "available on your PYTHONPATH environment variable? Did you "
        "forget to activate a virtual environment?"
    ) from exc

def drop_fk():
    django.setup()
    with connection.cursor() as cursor:
        # 尝试删除报错的外键约束
        fk_name = 'user_part_id_id_536abfa8_fk_部门表_id'
        table_name = 'user' 
        
        print(f"Attempting to drop Foreign Key {fk_name} from table {table_name}...")
        try:
            cursor.execute(f"ALTER TABLE `{table_name}` DROP FOREIGN KEY `{fk_name}`;")
            print("Foreign Key dropped successfully.")
        except Exception as e:
            print(f"Error dropping FK: {e}")
            # 尝试不带引号或不同的表名，如果之前失败
            
        # 很多时候 FK 也会建立索引，尝试删除索引以防万一（虽然主要阻止删除列的是 FK）
        print(f"Attempting to drop Key/Index {fk_name} from table {table_name}...")
        try:
            cursor.execute(f"ALTER TABLE `{table_name}` DROP KEY `{fk_name}`;")
            print("Key/Index dropped successfully.")
        except Exception as e:
            print(f"Error dropping Key: {e}")

if __name__ == '__main__':
    drop_fk()
